import { getUrlParams, storage } from "./utils";
function closeSelf() {
    if (parent) {
        const dialog = parent.document.querySelector<HTMLDialogElement>("#nodePropDialog")!;
        dialog.querySelector("iframe")!.src = "./view/blank.html";
        dialog.close();
        const mask = parent.document.querySelector<HTMLDivElement>(".mask")!;
        mask.style.display = "none";
    } else {
        window.close();
    }
}
// 记录的初始标识
let orginFlag = "";
const params = getUrlParams();

document.querySelector("form .quit")?.addEventListener("click", () => {
    closeSelf();
});
document.querySelector("form")?.addEventListener("submit", (evt) => {
    evt.preventDefault();
});

//处理提交时返回数据
export function handleSubmitForm(nodeFlag: string, handle?: (el: HTMLFormElement) => any, autoclose?: boolean) {
    orginFlag = nodeFlag;
    if (typeof handle != "function") {
        handle = (el: HTMLFormElement) => {
            const data = serializeForm(el);
            saveValue(nodeFlag, JSON.stringify(data));
        }
    }
    document.querySelector<HTMLButtonElement>("form .ok")?.addEventListener("click", () => {
        const flagVal = document.querySelector<HTMLInputElement>("#flag")?.value;
        if (!flagVal) {
            alert("请输入节点标识");
            return;
        }
        const obj = parent.document.querySelector(`[data-flag='${flagVal}']`);
        // 能查到一个，可能有重复，要看是否是当前节点的flag
        if (obj && orginFlag != flagVal) {
            alert("节点标识重复");
            return;
        }
        handle(document.querySelector("form")!);
        if (autoclose != false) {
            closeSelf();
        }
    });
}

export function setElementValue(el: string, paramName?: string): string {
    paramName = paramName ?? el;
    const obj = document.querySelector("#" + el) ?? document.querySelector(`[name="${el}"]`);
    let val = (params[paramName] ?? getStorageValue(paramName)) || "";
    if (obj) {
        obj.setAttribute("value", val);
    }
    return val;
}

// 通过sessionStorage保存后期再处理
function saveValue(name: string, value: any) {
    value = value ?? "";
    storage.setItem(name, value);
}

export function getStorageValue(name: string, storageKey?: string): Record<string, any> | null {
    storageKey = storageKey ?? params["flag"];
    if (storageKey) {
        const str = storage.getItem(storageKey);
        if (str) {
            return JSON.parse(str)[name];
        }
    }
    return null;
}

export function serializeForm(form: HTMLFormElement): Record<string, any> {
    const formData = new FormData(form);
    const json = <Record<string, any>>{};
    // 遍历 FormData 并转换为 JSON
    for (const [key, value] of formData.entries()) {
        // 处理多值字段（如复选框组 name="hobbies[]"）
        if (json.hasOwnProperty(key)) {
            if (!Array.isArray(json[key])) {
                json[key] = [json[key]];
            }
            json[key].push(value);
        } else {
            json[key] = value;
        }
    }
    return json;
}
